<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>简单删除测试</title>
    <style>
        body { font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto; padding: 20px; }
        .container { border: 1px solid #ddd; padding: 20px; border-radius: 5px; }
        .form-group { margin-bottom: 15px; }
        label { display: block; margin-bottom: 5px; }
        input[type="number"] { width: 100%; padding: 8px; box-sizing: border-box; }
        button { padding: 10px 15px; background-color: #d9534f; color: white; border: none; border-radius: 4px; cursor: pointer; }
        button:hover { background-color: #c9302c; }
        #status { margin-top: 20px; padding: 10px; border-radius: 4px; }
        .success { background-color: #dff0d8; color: #3c763d; }
        .error { background-color: #f2dede; color: #a94442; }
        .debug-info { margin-top: 20px; padding: 10px; background-color: #f8f9fa; border-radius: 4px; font-family: monospace; white-space: pre-wrap; }
    </style>
</head>
<body>
    <div class="container">
        <h1>简单项目删除测试</h1>
        <div id="debug-info" class="debug-info"></div>
        <form id="delete-form" method="POST">
            {% csrf_token %}
            <div class="form-group">
                <label for="project-id">项目ID:</label>
                <input type="number" id="project-id" name="project_id" min="1" required>
            </div>
            <button type="submit">删除项目</button>
        </form>
        <div id="status"></div>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const form = document.getElementById('delete-form');
            const statusDiv = document.getElementById('status');
            const projectIdInput = document.getElementById('project-id');
            const debugInfoDiv = document.getElementById('debug-info');

            // 添加调试信息
            addDebugInfo('页面加载完成');
            addDebugInfo(`当前URL: ${window.location.href}`);

            // 显示CSRF令牌值（用于调试）
            const csrfToken = document.querySelector('input[name="csrfmiddlewaretoken"]').value;
            addDebugInfo(`CSRF令牌: ${csrfToken}`);

            // 检查登录状态
            checkLoginStatus();

            form.addEventListener('submit', function(e) {
                e.preventDefault();
                const projectId = projectIdInput.value;

                if (!projectId || isNaN(projectId) || parseInt(projectId) <= 0) {
                    showStatus('请输入有效的项目ID', true);
                    return;
                }

                if (confirm(`确定要删除ID为 ${projectId} 的项目吗？`)) {
                    const deleteUrl = `/project/delete/${projectId}/`;
                    addDebugInfo(`准备提交删除请求到: ${deleteUrl}`);
                    showStatus('正在提交删除请求...', false);

                    // 使用XMLHttpRequest提交请求
                    const xhr = new XMLHttpRequest();
                    xhr.open('POST', deleteUrl, true);
                    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
                    xhr.onreadystatechange = function() {
                        if (xhr.readyState === 4) {
                            addDebugInfo(`请求完成，状态码: ${xhr.status}`);
                            addDebugInfo(`响应内容: ${xhr.responseText}`);

                            try {
                                const response = JSON.parse(xhr.responseText);
                                if (xhr.status === 200) {
                                    if (response.status) {
                                        showStatus('项目删除成功', false);
                                        addDebugInfo('项目删除成功，3秒后跳转到项目列表...');
                                        setTimeout(() => {
                                            window.location.href = '/project/list/';
                                        }, 3000);
                                    } else {
                                        showStatus(`删除失败: ${response.msg}`, true);
                                    }
                                } else {
                                    showStatus(`请求失败，状态码: ${xhr.status}`, true);
                                }
                            } catch (e) {
                                showStatus('解析响应失败: ' + e.message, true);
                                addDebugInfo('解析响应错误: ' + e.message);
                            }
                        }
                    };

                    xhr.onerror = function() {
                        showStatus('请求发生错误', true);
                        addDebugInfo('请求发生错误');
                    };

                    xhr.timeout = 5000;
                    xhr.ontimeout = function() {
                        showStatus('请求超时', true);
                        addDebugInfo('请求超时');
                    };

                    // 发送CSRF令牌和项目ID
                    const data = `csrfmiddlewaretoken=${encodeURIComponent(csrfToken)}&project_id=${encodeURIComponent(projectId)}`;
                    xhr.send(data);
                    addDebugInfo('请求已发送');
                }
            });

            function showStatus(message, isError) {
                statusDiv.textContent = message;
                statusDiv.className = isError ? 'error' : 'success';
            }

            function addDebugInfo(message) {
                const timestamp = new Date().toLocaleTimeString();
                debugInfoDiv.textContent += `[${timestamp}] ${message}\n`;
                console.log(`[${timestamp}] ${message}`);
            }

            function checkLoginStatus() {
                addDebugInfo('检查登录状态...');
                const xhr = new XMLHttpRequest();
                xhr.open('GET', '/web/code/', true);
                xhr.onreadystatechange = function() {
                    if (xhr.readyState === 4) {
                        if (xhr.status === 200) {
                            addDebugInfo('登录状态检查成功: 用户已登录');
                        } else if (xhr.status === 302) {
                            addDebugInfo('登录状态检查: 用户未登录，被重定向');
                            showStatus('您未登录，请先登录', true);
                        } else {
                            addDebugInfo(`登录状态检查失败，状态码: ${xhr.status}`);
                        }
                    }
                };
                xhr.send();
            }
        });
    </script>
</body>
</html>